//
//  PayViewController.m
//  car
//
//  Created by chenxu on 4/9/15.
//  Copyright (c) 2015 chenxu. All rights reserved.
//

#import "PayViewController.h"
#import "NetAPIManager.h"
#import "price_cell.h"
#import "Input_LeftRightLabel_Cell.h"
#import "Input_LeftImage_Cell.h"
#import "LeftImage_RightButton_Cell.h"
#import "carinfo_cell.h"
#import "InputOnlyTextPlainCell.h"
#import "LeftImg_cell.h"
#import "Insurance.h"
#import "AlipayHeader.h"
#import "Input_LeftImage_RightImage_Cell.h"
#import <SMS_SDK/SMS_SDK.h>

#define kCellIdentifier_price @"price_cell"
#define kCellIdentifier_contact @"contact_cell"
#define kCellIdentifier_carinfo @"carinfo_cell"
#define kCellIdentifier_normal @"normal_cell"
#define kCellIdentifier_inputplain @"input_cell"
#define kCellIdentifier_button @"button_cell"
#define kCellIdentifier_yanzhenma @"yanzhenma_cell"
#define kCellIdentifier_checkbox @"checkbox_cell"

@interface PayViewController ()
@property (strong,nonatomic) NSArray* insarr;
@property (strong,nonatomic) NSString *address,*contactor;
@property (strong,nonatomic) NSString *capture,*phone;//验证码
@property (strong,nonatomic) NSString *owner,*ownerid,*benefiter,*beneid;
@property BOOL isowner;
@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _mytableview.tableFooterView = [self tableFooterView];
    [_mytableview registerClass:[UITableViewCell class] forCellReuseIdentifier:kCellIdentifier_normal];
    [_mytableview registerClass:[price_cell class] forCellReuseIdentifier:kCellIdentifier_price];
    [_mytableview registerClass:[Input_LeftRightLabel_Cell class] forCellReuseIdentifier:kCellIdentifier_contact];
    [_mytableview registerClass:[LeftImage_RightButton_Cell class] forCellReuseIdentifier:kCellIdentifier_button];
    [_mytableview registerClass:[carinfo_cell class] forCellReuseIdentifier:kCellIdentifier_carinfo];
    [_mytableview registerClass:[Input_LeftImage_RightImage_Cell class] forCellReuseIdentifier:kCellIdentifier_yanzhenma];
    _insarr = _myorder.insurances;
    [_mytableview registerClass:[LeftImg_cell class] forCellReuseIdentifier:kCellIdentifier_checkbox];
    
    //获取车辆信息
    [[NetAPIManager sharedManager] request_cars:[[Login curLoginUser] tousernameParams] andBlock:^(id data, NSError *error) {
        if (data) {
            for (int i=0; i< [(NSArray*)data count]; i++) {
                Car* car = [NSObject objectOfClass:@"Car" fromJSON:[data objectAtIndex:i]];
                if ([car.Cid isEqual:_myorder.Cid]) {
                    _mycar = car;
                    [_mytableview reloadData];
                }
            }
        }
    }];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(payfinished) name:@"alipay" object:nil];
    _address = [Login curLoginUser].Address;
    _contactor = [Login curLoginUser].Nickname;
    _phone = [Login curLoginUser].Phone;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (UIView*)tableFooterView{
    
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 90)];
    
    UIButton *saveBtn = [UIButton buttonWithStyle:StrapThemeStyle andTitle:@"提交订单" andFrame:CGRectMake(30, 25, kScreen_Width-30*2, 35) target:self action:@selector(pay)];
    [saveBtn setPopingPressed];
    [footerV addSubview:saveBtn];
    return footerV;
}

#pragma mark logic
- (void)pay{

    
    if (!_owner || !_ownerid || !_capture || !_phone || !_address || !_contactor) {
        [self showHudTipStr:@"请填写完整"];
        return;
    }
    if (_isowner && (!_benefiter || !_beneid)){
        [self showHudTipStr:@"请填写受益人信息"];
        return;
    }
    else{
        [SMS_SDK commitVerifyCode:_capture result:^(enum SMS_ResponseState state) {
            //短信验证成功
            if (state == SMS_ResponseStateSuccess) {
                [AlipayRequestConfig alipayWithPartner:kPartnerID seller:kSellerAccount tradeNO:_myorder.Orderid productName:@"百车易车险" productDescription:_myorder.Orderid amount:[self getsum] notifyURL:kNotifyURL itBPay:@"30m"];
            }
            else{
                [self showHudTipStr:@"验证码错误"];
            }
        }];
        
    }
}

- (void)payfinished{
    [[NetAPIManager sharedManager]finish_order:[_myorder toOrderidParams]  andBlock:^(id data, NSError *error) {
        [[NetAPIManager sharedManager]submit_order:[self toParams] andBlock:^(id data, NSError *error) {
            NSInteger count = [self.navigationController.viewControllers count];
            //跳回上一页
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:count-3] animated:YES ];
            [self showHudTipStr:@"交易成功"];
        }];
    }];
    
    
}

- (NSDictionary*)toParams{
    if (_isowner) {
        return @{
                 @"Username"    :_myorder.Username,
                 @"Chezhuname"  :_owner,
                 @"Chezhuid"    :_ownerid,
                 @"Shouyiname"  :_benefiter,
                 @"Shouyiid"    :_beneid
                 };
    }
    else{
        return @{
                 @"Username"    :_myorder.Username,
                 @"Chezhuname"  :_owner,
                 @"Chezhuid"    :_ownerid,
                 @"Shouyiname"  :@"",
                 @"Shouyiid"    :@""
                 };
    }
}

#pragma mark Table M
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSUInteger  ret = 0;
    switch (section) {
        case 0:
            ret = [_mycar numberOfRow];
            break;
            
        case 1:
            ret = _myorder.insurances.count+1;
            break;
            
        case 2:
            ret = 2;
            break;
          
        case 3:
            if (!_isowner) {
                ret = 3;
            }
            else{
                ret = 5;
            }
            break;
            
        case 4:
            ret = 2;
            break;
            
        default:
            break;
    }
    return ret;
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString * ret = @"";
    switch (section) {
        case 0:
            ret = @"车辆信息";
            break;
            
        case 1:
            ret = @"车险金额详单";
            break;
            
        case 2:
            ret = @"配送地址";
            break;
            
        case 3:
            ret = @"个人信息";
            break;
        
        default:
            break;
    }
    return ret;
}


- (NSString*)getsum{
    NSInteger ret = 0;
    for (int i=0; i<_myorder.insurances.count; i++) {
        Insurance* ins = [_myorder.insurances objectAtIndex:i];
        ret += [ins.price integerValue];
    }
    NSString* str = [NSString stringWithFormat:@"%ld",(long)ret];
    return str;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section == 0) {//车辆信息
        
        carinfo_cell* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_carinfo forIndexPath:indexPath];
        NSString* title  = [_mycar titleAtIndex:(int)indexPath.row];
        NSString* value  = [_mycar contentAtIndex:(int)indexPath.row];
        [cell setLeft:title right:value];
        return cell;
    }
    else if (indexPath.section == 1){//金额
     
        if (indexPath.row < _myorder.insurances.count) {
            price_cell* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_price forIndexPath:indexPath];
            Insurance* ins = [_myorder.insurances objectAtIndex:indexPath.row];
            [cell setLeft:ins.xianming right:ins.price cellType:price_normal];
            return cell;
        }
        else{
            price_cell* cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_price forIndexPath:indexPath];
            [cell setLeft:@"共计" right:[self getsum] cellType:price_total];
            return cell;
        }
    }
    else if (indexPath.section == 2)//配送地址
    {
        Input_LeftImage_Cell *cell = [[[NSBundle mainBundle] loadNibNamed:@"Input_LeftImage_Cell" owner:self options:nil] firstObject];
        if (indexPath.row==0) {
            [cell configWithImgName:@"address" andLabel:@"邮寄地址" andPlaceholder:@"请输入邮寄地址" andValue:_address ];
            cell.textValueChangedBlock = ^(NSString* text){
                _address =  text;
            };
        }
        else{
            [cell configWithImgName:@"nicheng" andLabel:@"联系人" andPlaceholder:@"请输入联系人" andValue:_contactor];
            cell.textValueChangedBlock = ^(NSString* text){
                _contactor =  text;
            };
        }
       
        return cell;
    }
    else if (indexPath.section == 3)//个人信息
    {
        if (indexPath.row < 2) {
            Input_LeftRightLabel_Cell *cell = [[[NSBundle mainBundle] loadNibNamed:@"Input_LeftRightLabel_Cell" owner:self options:nil] firstObject];
            if (indexPath.row==0) {
                [cell configWithLeftLabel:@"车主姓名" andRightLabel:@"" andPlaceholder:@"请填写" andValue:_owner];
                cell.textValueChangedBlock = ^(NSString* text){
                    _owner =  text;
                };
            }
            else{
                [cell configWithLeftLabel:@"车主身份证号" andRightLabel:@"" andPlaceholder:@"请填写" andValue:_ownerid];
                cell.textValueChangedBlock = ^(NSString* text){
                    _ownerid =  text;
                };
            }
            return cell;
        }
        else if (indexPath.row==2){
            LeftImg_cell* cell =  [[[NSBundle mainBundle] loadNibNamed:@"LeftImg_cell" owner:self options:nil] firstObject];

            if (!_isowner) {
                cell.LeftImg.image = [UIImage imageNamed:@"cb_normal"];
            }
            else{
                cell.LeftImg.image = [UIImage imageNamed:@"cb_checked"];
            }
            cell.title.text = @"受益人是否同为车主";
            return cell;
        }
        
        //多余的选项
        if(!_isowner){
            return nil;
        }
        else{
            Input_LeftRightLabel_Cell *cell = [[[NSBundle mainBundle] loadNibNamed:@"Input_LeftRightLabel_Cell" owner:self options:nil] firstObject];
            cell.tapInsideBlock = ^(){
                [UIView up:self.mytableview length:150];
            };
            cell.endinputBlock = ^(){
                [UIView down:self.mytableview];
            };
            if (indexPath.row==3) {
                [cell configWithLeftLabel:@"受益人姓名" andRightLabel:@"" andPlaceholder:@"请填写" andValue:_owner];
                cell.textValueChangedBlock = ^(NSString* text){
                    _benefiter =  text;
                };
            }
            else if(indexPath.row == 4){
                [cell configWithLeftLabel:@"受益人身份证号" andRightLabel:@"" andPlaceholder:@"请填写" andValue:_ownerid];
                cell.textValueChangedBlock = ^(NSString* text){
                    _beneid =  text;
                };
            }
            return cell;
        }
    }
    else//手机验证
    {
        if (indexPath.row==0) {
            Input_LeftImage_Cell *cell = [[[NSBundle mainBundle] loadNibNamed:@"Input_LeftImage_Cell" owner:self options:nil] firstObject];
            [cell configWithImgName:@"phonenumber" andLabel:@"手机号" andPlaceholder:@"请填写手机号" andValue:_phone];
            cell.editBeginBlock = ^{
                [UIView up:self.mytableview length:150];
            };
            cell.textValueChangedBlock = ^(NSString* number){
                _phone = number;
            };
            cell.pressreturn = ^(NSString* phone){
                [UIView down:self.mytableview];
            };
            return cell;

        }
        else{
            Input_LeftImage_RightImage_Cell *cell = [[[NSBundle mainBundle] loadNibNamed:@"Input_LeftImage_RightImage_Cell" owner:self options:nil] firstObject];
            cell.leftimg.image = [UIImage imageNamed:@"email"];
            [cell.rightBtn setTitle:@"获取" forState:UIControlStateNormal];
            cell.title.text = @"验证码";
            cell.input.placeholder = @"填写验证码";
            cell.valueChanged = ^(NSString *str){
                _capture = str;
                [UIView up:self.mytableview length:150];
            };
            cell.editEnd = ^(NSString* str){
                _capture = str;
                [UIView down:self.mytableview];
            };
            //获取验证码
            cell.buttonClicked = ^(){
                NSLog(@"获取验证码");
                NSLog(@"%@",_phone);
                [SMS_SDK getVerificationCodeBySMSWithPhone:_phone zone:@"86" result:^(SMS_SDKError *error) {
                    if (!error)
                    {
                        NSString * tip = [NSString stringWithFormat:@"已发送到您的手机:+86 %@",_phone];
                        [self showHudTipStr:tip];
                    }
                    else
                    {
                        UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"codesenderrtitle", nil)
                                                                      message:[NSString stringWithFormat:@"状态码：%zi ,错误描述：%@",error.errorCode,error.errorDescription]
                                                                     delegate:self
                                                            cancelButtonTitle:NSLocalizedString(@"sure", nil)
                                                            otherButtonTitles:nil, nil];
                        [alert show];
                    }
                    
                }];
            };
            return cell;

        }
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 3 && indexPath.row == 2) {
        _isowner = _isowner?false:true;
        [tableView reloadData];
    }
}
@end
